package com.example.myhotel.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.myhotel.common.BaseContext;
import com.example.myhotel.common.R;
import com.example.myhotel.common.UserThreadLocal;
import com.example.myhotel.entity.Customers;
import com.example.myhotel.service.BookService;
import com.example.myhotel.service.CustomersService;
import com.example.myhotel.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@CrossOrigin
@Slf4j
public class CustomersController {
    @Autowired
    private CustomersService customersService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private BookService bookService;
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize){
        Page<Customers> userPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Customers> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Customers::getCreateTime);
        customersService.page(userPage,wrapper);
        return R.success(userPage);
    }
    @PostMapping("/save")
    public R<String> save(@RequestBody Customers customers){
        String phone = customers.getPhone();
        LambdaQueryWrapper<Customers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customers::getPhone,phone);
        Customers customersServiceOne = customersService.getOne(wrapper);
        if (customersServiceOne !=null){
            return R.error("手机号已注册");
        }else {
            customers.setPassword(DigestUtils.md5DigestAsHex(customers.getPassword().getBytes()));
            customersService.save(customers);
            return R.success("注册成功");
        }
    }

    @PostMapping("login")
    public R<String> login(@RequestBody Customers customers, HttpServletRequest request){
        LambdaQueryWrapper<Customers> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Customers::getName,customers.getName());
        List<Customers> list = customersService.list(wrapper);
        wrapper.eq(Customers::getPhone,customers.getPhone());
        Customers one = customersService.getOne(wrapper);
        if (list.isEmpty()){
            return R.error("对不起你还没注册");
        }
        if ( one==null){
            return R.error("输入的手机号有误");
        }
        String password = DigestUtils.md5DigestAsHex(customers.getPassword().getBytes());
        if (!one.getPassword().equals(password)){
             return R.error("密码错误");
        }
        //一开始redis登录的方法
/*
        String token = UUID.randomUUID().toString();
        //redis数据库设置数据和缓存时间

        stringRedisTemplate.opsForValue().set("userId",one.getId(),30,TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set("uToken",token,30,TimeUnit.MINUTES);
        //在session写入userid
        request.getSession().setAttribute("userId",one.getId());
        Map<String,Object> map = new HashMap<>();
        map.put("uToken",token);
        map.put("tokenUser",one.getId());
        return R.success(map);*/

        String token = JWTUtils.createToken(one.getId(),password);
        stringRedisTemplate.opsForValue().set("TOKEN_"+token,JSON.toJSONString(one),1,TimeUnit.DAYS);
        return R.success(token);
    }
    @GetMapping("getUser")
    public R<Customers> getUser(){
        String userId = BaseContext.getCurrentId();
        Customers customers = customersService.getById(userId);
        if (customers != null){
            return R.success(customers);
        }
        return R.error("该用户已不存在");
    }
    @PutMapping
    public R<String> update(@RequestBody Customers customers){
        log.error("customers -------{}",customers);

        LambdaQueryWrapper<Customers> wrapper = new LambdaQueryWrapper<>();
        if (customers.getPassword() != null){//md5加密
            String password = DigestUtils.md5DigestAsHex(customers.getPassword().getBytes());
            customers.setPassword(password);
            customersService.update(customers,wrapper);
            return R.success("密码修改成功");
        }

        wrapper.eq(Customers::getId,customers.getId());

        customersService.update(customers,wrapper);
        return R.success("成功修改");
    }

    @DeleteMapping
    public R<String > delUser(String userId){
        log.info("delUserid:{}",userId);
        boolean chekBook = bookService.chekBook(userId,null);
        if (chekBook){
            customersService.removeById(userId);
            bookService.deleteBook(userId,null);
            return R.success("成功删除");
        }
        return R.error("删除失败，该用户有预定");

    }

}
